import os
import threading
import utils
import datetime
import schedule
import json
import pandas as pd
from pygame import mixer
from views import Ui_MainWindow
from PyQt5.QtGui import QStandardItemModel, QStandardItem
from PyQt5.QtCore import QStringListModel
from PyQt5.QtWidgets import QMainWindow, QMessageBox, QApplication


class mainController(QMainWindow, Ui_MainWindow):

    infos: list = []
    qList: list = []
    going: bool = False
    st = ''
    saveData: dict = {}

    def __init__(self, rootPath) -> None:
        super().__init__()
        self.setupUi(self)

        # 根目录
        self.rootPath = rootPath
        # json存储文件
        self.saveFile = os.path.join(self.rootPath, "save.txt")
        # 音频文件定位
        self.sound = os.path.join(self.rootPath, 'sound.mp3')
        # 初始化声音
        mixer.init()
        mixer.music.load(self.sound)
        # 定义列表数据
        self.listModel = QStringListModel([])
        # 绑定数据
        self.message.setModel(self.listModel)
        # listview 的点击事件
        self.message.doubleClicked.connect(self.clickedlist)
        # 清空消息事件
        self.clearBtn.clicked.connect(self.clearMessage)
        # 开始监听
        self.startBtn.clicked.connect(self.run)
        # 历史保存数据初始化
        self.initSaveData()
        # 加载监听数据
        self.loadTableView()

    def loadTableView(self):
        file = os.path.join(self.rootPath, 'watch.txt')
        if not os.path.exists(file):
            QMessageBox.critical(None, "错误", "目录下未发现watch.txt文件，请自行添加！")
        else:
            with open(file, 'r', encoding='utf-8') as f:
                for line in f.readlines():
                    line = line.strip('\n')
                    line = line.split("@")
                    line[3] = "个股" if line[3] == "1" else "板块"
                    self.infos.append(line)
            f.close()
        # print(self.infos)
        # 创建 model 表格
        model = QStandardItemModel(len(self.infos), 5)
        model.setHorizontalHeaderLabels(["股票代号", "名称", '换手率', '类型', '时段'])
        self.watchList.setModel(model)
        self.watchList.setColumnWidth(0, 100)
        self.watchList.setColumnWidth(1, 100)
        self.watchList.setColumnWidth(2, 100)
        self.watchList.setColumnWidth(3, 60)
        self.watchList.setColumnWidth(4, 60)

        for index, val in enumerate(self.infos):
            col = index
            model.setItem(col, 0, QStandardItem(val[0]))
            model.setItem(col, 1, QStandardItem(val[1]))
            model.setItem(col, 2, QStandardItem(val[2]))
            model.setItem(col, 3, QStandardItem(val[3]))
            model.setItem(col, 4, QStandardItem(val[4]))

    def playSound(self):
        mixer.music.play()

    def appendListView(self, item):
        threading.Thread(
            target=self.playSound, args=(), daemon=True).start()
        row_count = self.listModel.rowCount()
        self.listModel.insertRow(row_count)
        index = self.listModel.index(row_count)
        self.listModel.setData(index, item)

    def clearMessage(self):
        self.listModel.removeRows(0, self.listModel.rowCount())

    def clickedlist(self, qModelIndex):
        print(qModelIndex)
        clipboard = QApplication.clipboard()
        clipboard.setText(self.qList[qModelIndex.row()])

    def initSaveData(self):
        if not os.path.exists(self.saveFile):
            file = open(self.saveFile, 'w')
            file.close()
        else:
            f = open(self.saveFile, encoding='utf-8')
            data = f.read()
            if data != "":
                self.saveData = json.loads(data)

    def calculate(self):
        period = '5'  # 分钟线
        howDay = 0  # 一共往回计算几天，由watch.txt配置决定
        oneDayMany = 1  # 对应分钟线一天有几次记录
        today = datetime.date.today()
        threeMonthAgo = today - pd.offsets.MonthEnd(n=3)
        start = threeMonthAgo.strftime("%Y-%m-%d") + " 09:00:00"
        end = today.strftime("%Y-%m-%d") + " 18:00:00"
        for val in self.infos:
            howDay = int(val[4])
            s = utils.Stock(
                symbol=val[0],
                start_date=start,
                end_date=end,
                period=period).getSingle()
            s = s.to_dict(orient="records")
            data = s[(-abs(howDay) * oneDayMany):]

            changeRate = float(val[2])
            for item in data:
                if item["换手率"] > changeRate:
                        self.qList.append(val[0])
                        self.appendListView(
                            val[1] + "|日期：" + str(item["时间"]))
                        # 写入存储
                        time = datetime.datetime.strptime(
                            str(item["时间"]), "%Y-%m-%d %H:%M:%S").timestamp()
                        self.saveData[val[0]] = {"time": int(time), "changeRate": changeRate}
                        file_handle = open(self.saveFile, mode='w')
                        file_handle.write(json.dumps(self.saveData))
                        file_handle.close()

            """ 金钗银钗需要用到
            low = ''
            # 修改low参数。当记录的数据存在，且发生在设定日之内，替换low值
            if val[0] in self.saveData.keys():
                nowStamp = int(datetime.datetime.now().timestamp())

                # 权重加减，当为周六日则需要平衡
                weight: int = 0
                for days in range(0, howDay):
                    tempDate = datetime.date.today() - datetime.timedelta(days=days)
                    if tempDate.weekday() in [5, 6]:
                        weight += 1

                if (nowStamp - self.saveData[val[0]]["time"]) < ((howDay + weight) * 86400):
                    low = self.saveData[val[0]]["low"]
            
                    
            diff = float(val[2])
            for item in data:
                if low == '' or low > item["最低"]:
                    low = item["最低"]
                    if item["talib_DIFF"] > diff:
                        # print(str(low) + "====" + str(item["最低"]) +'|||||'+str(diff) +'=====' + str(item["talib_DIFF"]))
                        self.qList.append(val[0])
                        self.appendListView(
                            val[1] + "|日期：" + str(item["时间"]))
                        # 写入存储
                        time = datetime.datetime.strptime(
                            str(item["时间"]), "%Y-%m-%d %H:%M:%S").timestamp()
                        self.saveData[val[0]] = {"time": int(time), "low": low}
                        file_handle = open(self.saveFile, mode='w')
                        file_handle.write(json.dumps(self.saveData))
                        file_handle.close()
            """

    def threadSchedule(self):
        while self.going:
            schedule.run_pending()

    def run(self):
        if self.going == False:
            self.going = True
            threading.Thread(
                target=self.calculate,
                args=(),
                daemon=True).start()
            schedule.every(5).minutes.do(self.calculate)
            self.st = threading.Thread(
                target=self.threadSchedule, args=(), daemon=True)
            self.st.start()
            self.startBtn.setText("停止")
        else:
            self.going = False
            schedule.clear()
            self.startBtn.setText("开始")
